import 'package:loxen/api/http_server/user_follower.dart';
import 'package:loxen/mode/mine/user_follower_list.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:rxdart/rxdart.dart';

class MineFollowerViewModel extends BaseViewModel with UserFollowerMixin {
  Map<String, List<Follower>> _map = {};
  final int pageSize = 6;

  //加载数据
  void loadData() {
    userFollowerList(pageSize: pageSize.toString()).doOnListen(() {
      mState = BaseState.LOADING;
      notifyListeners();
    }).listen((event) {
      if (event != null && event.count > 0) {
        _map.putIfAbsent('0', () => event.results);
        mState = BaseState.CONTENT;
      } else {
        mState = BaseState.EMPTY;
      }
    }, onError: (error, stackTrace) {
      mState = BaseState.FAIL;
      print(error);
      print(stackTrace);
    }, onDone: () => notifyListeners());
  }

  // 加载下一页数据
  Future<List<Follower>> nextData(int page) async {
    if (_map.containsKey(page.toString())) {
      return _map[page.toString()];
    } else {
      var data = await userFollowerList(page: (page + 1).toString()).first;
      _map.putIfAbsent(page.toString(), () => data.results);
      return data.results;
    }
  }

  //刷新列表内容
  void refresh() {
    _map.clear();
  }

  // 取消关注
  cancelFollow(Follower entity, List<Follower> list,
      {Function() onSuccess, Function(String error) onError}) {
    unFollowerUser(entity.user.userId.toString()).listen((event) {
      if (event == 200) {
        list.remove(entity);
        _map.forEach((key, value) {
          value.remove(entity);
        });
        if (onSuccess != null) onSuccess.call();
        notifyListeners();
      } else {
        if (onError != null) onError.call('取消失败');
      }
    }, onError: (error, stack) {
      print(error);
      print(stack);
      if (onError != null) onError.call('网络异常');
    });
  }

}
